#include <errno.h>
#include <sys/sendfile.h>
#include "solaris_write_file_range.h"
#include "http_server.h"

int solaris_write_file_range (http_connection_t *http_connection, off_t to)
{
	/* Return values:
	 * -1: Error.
	 *  0: Send has been interrupted.
	 *  1: Range has been sent.
	 */

	struct sendfilevec vec;
	size_t xferred;

	vec.sfv_fd = http_connection->fd;
	vec.sfv_flag = 0;

	do {
		vec.sfv_off = http_connection->offset;
		vec.sfv_len = to - http_connection->offset + 1;

		if (sendfilev (http_connection->sd, &vec, 1, &xferred) < 0) {
			if (errno == EAGAIN) {
				return 0;
			} else if (errno == EINTR) {
				/* A signal occurred before any data was transmitted. */
				/* Add ourself to the list of interrupted HTTP connections. */
				http_server.interrupted_http_connections[http_server.number_interrupted_http_connections++] = http_connection;

				return 0;
			} else {
				return -1;
			}
		} else {
			http_connection->last_read_write = http_server.current_time;

			http_connection->sent += xferred;
			http_connection->offset += xferred;

			if (http_connection->offset >= to + 1) {
				/* We are done. */
				return 1;
			}
		}
	} while (1);
}
